home *** CD-ROM | disk | FTP | other *** search
/ Revista do CD-ROM 151 / cd-rom 151.iso / internet / firefox / Firefox Setup 3.0 Beta 1.exe / nonlocalized / components / nsBrowserGlue.js < prev    next >
Encoding:
Text File  |  2007-11-09  |  13.4 KB  |  393 lines

  1. //@line 37 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\nsBrowserGlue.js"
  2.  
  3. const Ci = Components.interfaces;
  4. const Cc = Components.classes;
  5. const Cr = Components.results;
  6. const Cu = Components.utils;
  7.  
  8. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  9. Cu.import("resource:///modules/distribution.js");
  10.  
  11. // Factory object
  12. const BrowserGlueServiceFactory = {
  13.   _instance: null,
  14.   createInstance: function (outer, iid) 
  15.   {
  16.     if (outer != null)
  17.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  18.     return this._instance == null ?
  19.       this._instance = new BrowserGlue() : this._instance;
  20.   }
  21. };
  22.  
  23. // Constructor
  24.  
  25. function BrowserGlue() {
  26.   this._init();
  27.   this._profileStarted = false;
  28. }
  29.  
  30. BrowserGlue.prototype = {
  31.   _saveSession: false,
  32.  
  33.   // nsIObserver implementation 
  34.   observe: function(subject, topic, data) 
  35.   {
  36.     switch(topic) {
  37.       case "xpcom-shutdown":
  38.         this._dispose();
  39.         break;
  40.       case "profile-before-change":
  41.         this._onProfileChange();
  42.         break;
  43.       case "profile-change-teardown": 
  44.         this._onProfileShutdown();
  45.         break;
  46.       case "prefservice:after-app-defaults":
  47.         this._onAppDefaults();
  48.         break;
  49.       case "final-ui-startup":
  50.         this._onProfileStartup();
  51.         break;
  52.       case "browser:purge-session-history":
  53.         // reset the console service's error buffer
  54.         const cs = Cc["@mozilla.org/consoleservice;1"].
  55.                    getService(Ci.nsIConsoleService);
  56.         cs.logStringMessage(null); // clear the console (in case it's open)
  57.         cs.reset();
  58.         break;
  59.       case "quit-application-requested":
  60.         this._onQuitRequest(subject, data);
  61.         break;
  62.       case "quit-application-granted":
  63.         if (this._saveSession) {
  64.           var prefBranch = Cc["@mozilla.org/preferences-service;1"].
  65.                            getService(Ci.nsIPrefBranch);
  66.           prefBranch.setBoolPref("browser.sessionstore.resume_session_once", true);
  67.         }
  68.         break;
  69.     }
  70.   }
  71.   // initialization (called on application startup) 
  72.   _init: function() 
  73.   {
  74.     // observer registration
  75.     const osvr = Cc['@mozilla.org/observer-service;1'].
  76.                  getService(Ci.nsIObserverService);
  77.     osvr.addObserver(this, "profile-before-change", false);
  78.     osvr.addObserver(this, "profile-change-teardown", false);
  79.     osvr.addObserver(this, "xpcom-shutdown", false);
  80.     osvr.addObserver(this, "prefservice:after-app-defaults", false);
  81.     osvr.addObserver(this, "final-ui-startup", false);
  82.     osvr.addObserver(this, "browser:purge-session-history", false);
  83.     osvr.addObserver(this, "quit-application-requested", false);
  84.     osvr.addObserver(this, "quit-application-granted", false);
  85.   },
  86.  
  87.   // cleanup (called on application shutdown)
  88.   _dispose: function() 
  89.   {
  90.     // observer removal 
  91.     const osvr = Cc['@mozilla.org/observer-service;1'].
  92.                  getService(Ci.nsIObserverService);
  93.     osvr.removeObserver(this, "profile-before-change");
  94.     osvr.removeObserver(this, "profile-change-teardown");
  95.     osvr.removeObserver(this, "xpcom-shutdown");
  96.     osvr.removeObserver(this, "prefservice:after-app-defaults");
  97.     osvr.removeObserver(this, "final-ui-startup");
  98.     osvr.removeObserver(this, "browser:purge-session-history");
  99.     osvr.removeObserver(this, "quit-application-requested");
  100.     osvr.removeObserver(this, "quit-application-granted");
  101.   },
  102.  
  103.   _onAppDefaults: function()
  104.   {
  105.     // apply distribution customizations (prefs)
  106.     // other customizations are applied in _onProfileStartup()
  107.     var distro = new DistributionCustomizer();
  108.     distro.applyPrefDefaults();
  109.   },
  110.  
  111.   // profile startup handler (contains profile initialization routines)
  112.   _onProfileStartup: function() 
  113.   {
  114.     // check to see if the EULA must be shown on startup
  115.     try {
  116.       var mustDisplayEULA = true;
  117.       var prefBranch = Cc["@mozilla.org/preferences-service;1"].
  118.                        getService(Ci.nsIPrefBranch);
  119.       var EULAVersion = prefBranch.getIntPref("browser.EULA.version");
  120.       mustDisplayEULA = !prefBranch.getBoolPref("browser.EULA." + EULAVersion + ".accepted");
  121.     } catch(ex) {
  122.     }
  123.  
  124.     if (mustDisplayEULA) {
  125.       var ww2 = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  126.                 getService(Ci.nsIWindowWatcher);
  127.       ww2.openWindow(null, "chrome://browser/content/EULA.xul", 
  128.                      "_blank", "chrome,centerscreen,modal,resizable=yes", null);
  129.     }
  130.  
  131.     this.Sanitizer.onStartup();
  132.     // check if we're in safe mode
  133.     var app = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).
  134.               QueryInterface(Ci.nsIXULRuntime);
  135.     if (app.inSafeMode) {
  136.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  137.                getService(Ci.nsIWindowWatcher);
  138.       ww.openWindow(null, "chrome://browser/content/safeMode.xul", 
  139.                     "_blank", "chrome,centerscreen,modal,resizable=no", null);
  140.     }
  141.  
  142.     // initialize Places
  143.     this._initPlaces();
  144.  
  145.     // apply distribution customizations
  146.     // prefs are applied in _onAppDefaults()
  147.     var distro = new DistributionCustomizer();
  148.     distro.applyCustomizations();
  149.  
  150.     // indicate that the profile was initialized
  151.     this._profileStarted = true;
  152.   },
  153.  
  154.   _onProfileChange: function()
  155.   {
  156.     // this block is for code that depends on _onProfileStartup() having 
  157.     // been called.
  158.     if (this._profileStarted) {
  159.       // final places cleanup
  160.       this._shutdownPlaces();
  161.     }
  162.   },
  163.  
  164.   // profile shutdown handler (contains profile cleanup routines)
  165.   _onProfileShutdown: function() 
  166.   {
  167.     // here we enter last survival area, in order to avoid multiple
  168.     // "quit-application" notifications caused by late window closings
  169.     const appStartup = Cc['@mozilla.org/toolkit/app-startup;1'].
  170.                        getService(Ci.nsIAppStartup);
  171.     try {
  172.       appStartup.enterLastWindowClosingSurvivalArea();
  173.  
  174.       this.Sanitizer.onShutdown();
  175.  
  176.     } catch(ex) {
  177.     } finally {
  178.       appStartup.exitLastWindowClosingSurvivalArea();
  179.     }
  180.   },
  181.  
  182.   _onQuitRequest: function(aCancelQuit, aQuitType)
  183.   {
  184.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  185.              getService(Ci.nsIWindowMediator);
  186.     var windowcount = 0;
  187.     var pagecount = 0;
  188.     var browserEnum = wm.getEnumerator("navigator:browser");
  189.     while (browserEnum.hasMoreElements()) {
  190.       windowcount++;
  191.  
  192.       var browser = browserEnum.getNext();
  193.       var tabbrowser = browser.document.getElementById("content");
  194.       if (tabbrowser)
  195.         pagecount += tabbrowser.browsers.length;
  196.     }
  197.  
  198.     this._saveSession = false;
  199.     if (pagecount < 2)
  200.       return;
  201.  
  202.     if (aQuitType != "restart")
  203.       aQuitType = "quit";
  204.  
  205.     var prefBranch = Cc["@mozilla.org/preferences-service;1"].
  206.                      getService(Ci.nsIPrefBranch);
  207.     var showPrompt = true;
  208.     try {
  209.       if (prefBranch.getIntPref("browser.startup.page") == 3 ||
  210.           prefBranch.getBoolPref("browser.sessionstore.resume_session_once"))
  211.         showPrompt = false;
  212.       else
  213.         showPrompt = prefBranch.getBoolPref("browser.warnOnQuit");
  214.     } catch (ex) {}
  215.  
  216.     var buttonChoice = 0;
  217.     if (showPrompt) {
  218.       var bundleService = Cc["@mozilla.org/intl/stringbundle;1"].
  219.                           getService(Ci.nsIStringBundleService);
  220.       var quitBundle = bundleService.createBundle("chrome://browser/locale/quitDialog.properties");
  221.       var brandBundle = bundleService.createBundle("chrome://branding/locale/brand.properties");
  222.  
  223.       var appName = brandBundle.GetStringFromName("brandShortName");
  224.       var quitDialogTitle = quitBundle.formatStringFromName(aQuitType + "DialogTitle",
  225.                                                               [appName], 1);
  226.       var quitTitle = quitBundle.GetStringFromName(aQuitType + "Title");
  227.       var cancelTitle = quitBundle.GetStringFromName("cancelTitle");
  228.       var saveTitle = quitBundle.GetStringFromName("saveTitle");
  229.       var neverAskText = quitBundle.GetStringFromName("neverAsk");
  230.  
  231.       var message;
  232.       if (aQuitType == "restart")
  233.         message = quitBundle.formatStringFromName("messageRestart",
  234.                                                   [appName], 1);
  235.       else if (windowcount == 1)
  236.         message = quitBundle.formatStringFromName("messageNoWindows",
  237.                                                   [appName], 1);
  238.       else
  239.         message = quitBundle.formatStringFromName("message",
  240.                                                   [appName], 1);
  241.  
  242.       var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  243.                           getService(Ci.nsIPromptService);
  244.  
  245.       var flags = promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
  246.                   promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
  247.                   promptService.BUTTON_POS_0_DEFAULT;
  248.       var neverAsk = {value:false};
  249.       if (aQuitType != "restart")
  250.         flags += promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_2;
  251.       buttonChoice = promptService.confirmEx(null, quitDialogTitle, message,
  252.                                    flags, quitTitle, cancelTitle, saveTitle,
  253.                                    neverAskText, neverAsk);
  254.  
  255.       switch (buttonChoice) {
  256.       case 0:
  257.         if (neverAsk.value)
  258.           prefBranch.setBoolPref("browser.warnOnQuit", false);
  259.         break;
  260.       case 1:
  261.         aCancelQuit.QueryInterface(Ci.nsISupportsPRBool);
  262.         aCancelQuit.data = true;
  263.         break;
  264.       case 2:
  265.         // could also set browser.warnOnQuit to false here,
  266.         // but not setting it is a little safer.
  267.         if (neverAsk.value)
  268.           prefBranch.setIntPref("browser.startup.page", 3);
  269.         break;
  270.       }
  271.  
  272.       this._saveSession = buttonChoice == 2;
  273.     }
  274.   },
  275.  
  276.   // returns the (cached) Sanitizer constructor
  277.   get Sanitizer() 
  278.   {
  279.     if(typeof(Sanitizer) != "function") { // we should dynamically load the script
  280.       Cc["@mozilla.org/moz/jssubscript-loader;1"].
  281.       getService(Ci.mozIJSSubScriptLoader).
  282.       loadSubScript("chrome://browser/content/sanitize.js", null);
  283.     }
  284.     return Sanitizer;
  285.   },
  286.  
  287.   /**
  288.    * Initialize Places
  289.    * - imports the bookmarks html file if bookmarks datastore is empty
  290.    */
  291.   _initPlaces: function bg__initPlaces() {
  292.     // we need to instantiate the history service before we check the 
  293.     // the browser.places.importBookmarksHTML pref, as 
  294.     // nsNavHistory::ForceMigrateBookmarksDB() will set that pref
  295.     // if we need to force a migration (due to a schema change)
  296.     var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
  297.                   getService(Ci.nsINavHistoryService);
  298.  
  299.     var importBookmarks = false;
  300.     try {
  301.       var prefBranch = Cc["@mozilla.org/preferences-service;1"].
  302.                        getService(Ci.nsIPrefBranch);
  303.       importBookmarks = prefBranch.getBoolPref("browser.places.importBookmarksHTML");
  304.     } catch(ex) {}
  305.  
  306.     if (!importBookmarks)
  307.       return;
  308.  
  309.     var dirService = Cc["@mozilla.org/file/directory_service;1"].
  310.                      getService(Ci.nsIProperties);
  311.  
  312.     var bookmarksFile = dirService.get("BMarks", Ci.nsILocalFile);
  313.  
  314.     if (bookmarksFile.exists()) {
  315.       // import the file
  316.       try {
  317.         var importer = 
  318.           Cc["@mozilla.org/browser/places/import-export-service;1"].
  319.           getService(Ci.nsIPlacesImportExportService);
  320.         importer.importHTMLFromFile(bookmarksFile, true);
  321.       } catch(ex) {
  322.       } finally {
  323.         prefBranch.setBoolPref("browser.places.importBookmarksHTML", false);
  324.       }
  325.  
  326.       // only back up pre-places bookmarks.html if we plan on overwriting it
  327.       if (prefBranch.getBoolPref("browser.bookmarks.overwrite")) {
  328.         // backup pre-places bookmarks.html
  329.         // XXXtodo remove this before betas, after import/export is solid
  330.         var profDir = dirService.get("ProfD", Ci.nsILocalFile);
  331.         var bookmarksBackup = profDir.clone();
  332.         bookmarksBackup.append("bookmarks.preplaces.html");
  333.         if (!bookmarksBackup.exists()) {
  334.           // save old bookmarks.html file as bookmarks.preplaces.html
  335.           try {
  336.             bookmarksFile.copyTo(profDir, "bookmarks.preplaces.html");
  337.           } catch(ex) {
  338.             dump("nsBrowserGlue::_initPlaces(): copy of bookmarks.html to bookmarks.preplaces.html failed: " + ex + "\n");
  339.           }
  340.         }
  341.       }
  342.     }
  343.   },
  344.  
  345.   /**
  346.    * Places shut-down tasks
  347.    * - back up and archive bookmarks
  348.    */
  349.   _shutdownPlaces: function bg__shutdownPlaces() {
  350.     // backup bookmarks to bookmarks.html
  351.     var importer =
  352.       Cc["@mozilla.org/browser/places/import-export-service;1"].
  353.       getService(Ci.nsIPlacesImportExportService);
  354.     importer.backupBookmarksFile();
  355.   },
  356.   
  357.   // ------------------------------
  358.   // public nsIBrowserGlue members
  359.   // ------------------------------
  360.   
  361.   sanitize: function(aParentWindow) 
  362.   {
  363.     this.Sanitizer.sanitize(aParentWindow);
  364.   },
  365.  
  366.   // for XPCOM
  367.   classDescription: "Firefox Browser Glue Service",
  368.   classID:          Components.ID("{eab9012e-5f74-4cbc-b2b5-a590235513cc}"),
  369.   contractID:       "@mozilla.org/browser/browserglue;1",
  370.  
  371.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
  372.                                          Ci.nsISupportsWeakReference,
  373.                                          Ci.nsIBrowserGlue]),
  374.  
  375.   // redefine the default factory for XPCOMUtils
  376.   _xpcom_factory: BrowserGlueServiceFactory,
  377.  
  378.   // get this contractID registered for certain categories via XPCOMUtils
  379.   _xpcom_categories: [
  380.     // make BrowserGlue a startup observer
  381.     { category: "app-startup", service: true }
  382.   ]
  383. }
  384.  
  385. //module initialization
  386. function NSGetModule(aCompMgr, aFileSpec) {
  387.   return XPCOMUtils.generateModule([BrowserGlue]);
  388. }
  389.  
  390.     
  391.  
  392.